<template>
  <view class="master-password-modal" v-if="visible">
    <view class="modal-overlay" @click="handleOverlayClick">
      <view class="modal-content" @click.stop>
        <!-- 模态框头部 -->
        <view class="modal-header">
          <text class="modal-title">{{ title }}</text>
          <view v-if="showClose" class="close-btn" @click="handleClose">
            <text class="close-icon">✕</text>
          </view>
        </view>

        <!-- 模态框内容 -->
        <view class="modal-body">
          <!-- 提示信息 -->
          <view v-if="description" class="description">
            <text>{{ description }}</text>
          </view>

          <!-- 密码输入 -->
          <view class="password-input-group">
            <view class="input-label">
              <text>主密码</text>
              <text v-if="isRequired" class="required">*</text>
            </view>

            <view class="password-input-wrapper">
              <input
                class="password-input"
                v-model="masterPassword"
                :password="!showPassword"
                placeholder="请输入主密码"
                :maxlength="50"
                @input="handleInput"
                @confirm="handleConfirm"
              />

              <view class="password-toggle" @click="togglePasswordVisibility">
                <text class="toggle-icon">{{ showPassword ? '🙈' : '👁️' }}</text>
              </view>
            </view>

            <!-- 错误提示 -->
            <view v-if="errorMessage" class="error-message">
              <text>{{ errorMessage }}</text>
            </view>
          </view>

          <!-- 加密方法选择 -->
          <view v-if="showEncryptMethod" class="encrypt-method-group">
            <view class="input-label">
              <text>加密方法</text>
            </view>

            <view class="encrypt-methods">
              <view
                v-for="method in encryptMethods"
                :key="method.value"
                class="method-item"
                :class="{ active: selectedMethod === method.value }"
                @click="selectMethod(method.value)"
              >
                <view class="method-info">
                  <text class="method-name">{{ method.name }}</text>
                  <text class="method-desc">{{ method.description }}</text>
                </view>
                <view class="method-indicator">
                  <text class="security-level" :class="method.security">
                    {{ method.securityText }}
                  </text>
                </view>
              </view>
            </view>
          </view>

          <!-- 生物识别选项 -->
          <view v-if="showBiometric && supportBiometric" class="biometric-group">
            <view
              class="biometric-option"
              :class="{ active: enableBiometric }"
              @click="toggleBiometric"
            >
              <view class="option-info">
                <text class="option-title">启用生物识别</text>
                <text class="option-desc">使用指纹或面容快速解锁</text>
              </view>
              <view class="option-switch">
                <text class="switch-icon">{{ enableBiometric ? '🔓' : '🔒' }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 模态框底部 -->
        <view class="modal-footer">
          <button
            v-if="showCancel"
            class="cancel-btn"
            @click="handleCancel"
          >
            取消
          </button>

          <button
            class="confirm-btn"
            :disabled="!canConfirm || isLoading"
            @click="handleConfirm"
          >
            {{ isLoading ? '验证中...' : confirmText }}
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { EncryptMethod } from '@/utils/crypto'
import { biometricAuth } from '@/utils/oauth'

interface MasterPasswordProps {
  visible: boolean
  title?: string
  description?: string
  isRequired?: boolean
  showClose?: boolean
  showCancel?: boolean
  showEncryptMethod?: boolean
  showBiometric?: boolean
  confirmText?: string
  defaultMethod?: EncryptMethod
}

interface MasterPasswordEmits {
  (event: 'confirm', data: { password: string; method?: EncryptMethod; biometric?: boolean }): void
  (event: 'cancel'): void
  (event: 'close'): void
}

const props = withDefaults(defineProps<MasterPasswordProps>(), {
  title: '输入主密码',
  description: '',
  isRequired: true,
  showClose: false,
  showCancel: true,
  showEncryptMethod: false,
  showBiometric: false,
  confirmText: '确认',
  defaultMethod: EncryptMethod.AES_256_GCM
})

const emit = defineEmits<MasterPasswordEmits>()

// 响应式数据
const masterPassword = ref('')
const showPassword = ref(false)
const errorMessage = ref('')
const isLoading = ref(false)
const selectedMethod = ref<EncryptMethod>(props.defaultMethod)
const enableBiometric = ref(false)
const supportBiometric = ref(false)

// 加密方法配置
const encryptMethods = [
  {
    value: EncryptMethod.AES_256_GCM,
    name: 'AES-256-GCM',
    description: '最强加密，推荐使用',
    security: 'high',
    securityText: '高'
  },
  {
    value: EncryptMethod.AES_256_CBC,
    name: 'AES-256-CBC',
    description: '强加密，兼容性好',
    security: 'high',
    securityText: '高'
  },
  {
    value: EncryptMethod.AES_128_GCM,
    name: 'AES-128-GCM',
    description: '快速加密',
    security: 'medium',
    securityText: '中'
  },
  {
    value: EncryptMethod.SM4,
    name: 'SM4',
    description: '国密算法',
    security: 'medium',
    securityText: '中'
  },
  {
    value: EncryptMethod.TripleDES,
    name: '3DES',
    description: '传统加密',
    security: 'low',
    securityText: '低'
  }
]

// 计算属性
const canConfirm = computed(() => {
  if (props.isRequired && !masterPassword.value.trim()) {
    return false
  }
  return true
})

// 监听
watch(() => props.visible, (newValue) => {
  if (newValue) {
    // 重置状态
    masterPassword.value = ''
    errorMessage.value = ''
    isLoading.value = false
    selectedMethod.value = props.defaultMethod
  }
})

// 页面加载
onMounted(() => {
  checkBiometricSupport()
})

// 检查生物识别支持
const checkBiometricSupport = async () => {
  try {
    // 检查平台是否支持生物识别
    const systemInfo = uni.getSystemInfoSync()
    supportBiometric.value = systemInfo.platform !== 'devtools' && systemInfo.platform !== 'h5'
  } catch (error) {
    supportBiometric.value = false
  }
}

// 处理输入
const handleInput = () => {
  errorMessage.value = ''
}

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

// 选择加密方法
const selectMethod = (method: EncryptMethod) => {
  selectedMethod.value = method
}

// 切换生物识别
const toggleBiometric = () => {
  enableBiometric.value = !enableBiometric.value
}

// 处理确认
const handleConfirm = async () => {
  if (!canConfirm.value || isLoading.value) return

  try {
    isLoading.value = true

    // 验证密码强度
    if (props.isRequired && masterPassword.value.length < 6) {
      errorMessage.value = '主密码至少需要6位字符'
      return
    }

    const data: { password: string; method?: EncryptMethod; biometric?: boolean } = {
      password: masterPassword.value
    }

    if (props.showEncryptMethod) {
      data.method = selectedMethod.value
    }

    if (props.showBiometric && supportBiometric.value) {
      data.biometric = enableBiometric.value
    }

    emit('confirm', data)

  } catch (error) {
    console.error('验证主密码失败:', error)
    errorMessage.value = '验证失败，请重试'
  } finally {
    isLoading.value = false
  }
}

// 处理取消
const handleCancel = () => {
  emit('cancel')
}

// 处理关闭
const handleClose = () => {
  emit('close')
}

// 处理遮罩层点击
const handleOverlayClick = () => {
  if (props.showClose) {
    handleClose()
  }
}
</script>

<style lang="scss" scoped>
.master-password-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;

  .modal-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
  }

  .modal-content {
    width: 100%;
    max-width: 400px;
    background: white;
    border-radius: 16px;
    overflow: hidden;
    animation: modalSlideIn 0.3s ease-out;
  }

  .modal-header {
    padding: 20px 20px 0;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .modal-title {
      font-size: 18px;
      font-weight: 600;
      color: #1a1a1a;
    }

    .close-btn {
      width: 28px;
      height: 28px;
      border-radius: 14px;
      background: #f5f5f5;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.2s;

      .close-icon {
        font-size: 14px;
        color: #666;
      }

      &:active {
        transform: scale(0.9);
        background: #e8e8e8;
      }
    }
  }

  .modal-body {
    padding: 20px;

    .description {
      margin-bottom: 20px;

      text {
        font-size: 14px;
        color: #666;
        line-height: 1.5;
      }
    }

    .password-input-group {
      margin-bottom: 20px;

      .input-label {
        display: flex;
        align-items: center;
        margin-bottom: 8px;

        text {
          font-size: 14px;
          color: #333;
          font-weight: 600;
        }

        .required {
          color: #ff4d4f;
          margin-left: 4px;
        }
      }

      .password-input-wrapper {
        position: relative;

        .password-input {
          width: 100%;
          padding: 16px 50px 16px 16px;
          background: #f8f9fa;
          border: 1px solid #e9ecef;
          border-radius: 8px;
          font-size: 16px;

          &::placeholder {
            color: #999;
          }

          &:focus {
            border-color: #1890ff;
            background: white;
          }
        }

        .password-toggle {
          position: absolute;
          right: 12px;
          top: 50%;
          transform: translateY(-50%);
          width: 32px;
          height: 32px;
          border-radius: 6px;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: all 0.2s;

          .toggle-icon {
            font-size: 16px;
            color: #666;
          }

          &:active {
            transform: translateY(-50%) scale(0.9);
            background: rgba(0, 0, 0, 0.05);
          }
        }
      }

      .error-message {
        margin-top: 8px;

        text {
          font-size: 12px;
          color: #ff4d4f;
        }
      }
    }

    .encrypt-method-group {
      margin-bottom: 20px;

      .input-label {
        margin-bottom: 12px;

        text {
          font-size: 14px;
          color: #333;
          font-weight: 600;
        }
      }

      .encrypt-methods {
        display: flex;
        flex-direction: column;
        gap: 8px;

        .method-item {
          padding: 12px;
          border: 1px solid #e9ecef;
          border-radius: 8px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          transition: all 0.2s;

          &.active {
            border-color: #1890ff;
            background: rgba(24, 144, 255, 0.05);
          }

          &:active {
            transform: scale(0.98);
          }

          .method-info {
            flex: 1;

            .method-name {
              display: block;
              font-size: 14px;
              color: #333;
              font-weight: 600;
              margin-bottom: 2px;
            }

            .method-desc {
              font-size: 12px;
              color: #666;
            }
          }

          .method-indicator {
            .security-level {
              font-size: 10px;
              padding: 2px 6px;
              border-radius: 4px;
              font-weight: 600;

              &.high {
                background: #f6ffed;
                color: #52c41a;
              }

              &.medium {
                background: #fff7e6;
                color: #fa8c16;
              }

              &.low {
                background: #fff2f0;
                color: #ff4d4f;
              }
            }
          }
        }
      }
    }

    .biometric-group {
      .biometric-option {
        padding: 12px;
        border: 1px solid #e9ecef;
        border-radius: 8px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        transition: all 0.2s;

        &.active {
          border-color: #1890ff;
          background: rgba(24, 144, 255, 0.05);
        }

        &:active {
          transform: scale(0.98);
        }

        .option-info {
          flex: 1;

          .option-title {
            display: block;
            font-size: 14px;
            color: #333;
            font-weight: 600;
            margin-bottom: 2px;
          }

          .option-desc {
            font-size: 12px;
            color: #666;
          }
        }

        .option-switch {
          .switch-icon {
            font-size: 16px;
          }
        }
      }
    }
  }

  .modal-footer {
    padding: 0 20px 20px;
    display: flex;
    gap: 12px;

    button {
      flex: 1;
      padding: 14px;
      border: none;
      border-radius: 8px;
      font-size: 16px;
      font-weight: 600;
      transition: all 0.2s;

      &:active {
        transform: scale(0.98);
      }

      &:disabled {
        opacity: 0.6;
        transform: none !important;
      }
    }

    .cancel-btn {
      background: #f6f6f6;
      color: #666;
    }

    .confirm-btn {
      background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
      color: white;
    }
  }
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-50px) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}
</style>